package com.zhangmengyuan.medical.controller;

import com.zhangmengyuan.medical.entity.Goods;
import com.zhangmengyuan.medical.entity.User;
import com.zhangmengyuan.medical.service.GoodsService;
import com.zhangmengyuan.medical.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;


    @PostMapping("login")
    public String login(@RequestParam(value = "password", required = false) String password,
                        @RequestParam(value = "username", required = false) String username,
                        HttpSession session, Model model) {
        User user = userService.login(username, password);
        if (null != user) {
            session.setAttribute("user", user);
            Page<Goods> list = goodsService.getAll(0);
            model.addAttribute("page", list);
            model.addAttribute("list", list.getContent());
            return "index";
        }
        return "login";
    }

    @GetMapping("/")
    public String toLogin() {
        return "login";
    }
}
